const db = require('../db')
const { getNowTime, formatTime } = require('../utils')
// 集成log4js日志
const log4js = require('../utils/log4js')
const logger = log4js.getLogger('runtime')

/**
 * 新增操作日志
 * @param {*} params
 */
exports.addOperation_log = (req, res, options) => {
  let username = ''
  let operation = req.method
  let method = req.method
  let params = JSON.stringify(req.body || req.params)
  let time = options.time
  let ip = req.headers.ip || ''
  let create_by = ''
  let create_time = getNowTime()
  let last_update_by = ''
  let last_update_time = getNowTime()

  if (!ip) return

  if (JSON.stringify(req.body) !== '{}') {
    !username && (username = req.body.username)
    !create_by && (create_by = req.body.userId || req.body.id)
    !last_update_by && (last_update_by = req.body.userId || req.body.id)
  }
  if (JSON.stringify(req.params) !== '{}') {
    !username && (username = req.params.username)
    !create_by && (create_by = req.params.userId || req.params.id)
    !last_update_by && (last_update_by = req.params.userId || req.params.id)
  }
  if (req.auth !== undefined && JSON.stringify(req.auth) !== '{}') {
    !username && (username = req.auth.username)
    !create_by && (create_by = req.auth.userId || req.auth.id)
    !last_update_by && (last_update_by = req.auth.userId || req.auth.id)
  }
  if (JSON.stringify(options) !== '{}') {
    !username && (username = options.username)
    !create_by && (create_by = options.userId || options.id)
    !last_update_by && (last_update_by = options.userId || options.id)
  }

  // 插入数据库
  const insertsql = 'insert into sys_operation_log set ?'
  db.query(
    insertsql,
    {
      username,
      operation,
      method,
      params,
      time,
      ip,
      create_by,
      create_time,
      last_update_by,
      last_update_time
    },
    (err, results) => {
      if (err) return logger.error('新增操作日志失败：' + err)
      if (results.affectedRows !== 1)
        logger.error('新增操作日志失败：' + insertsql)
    }
  )
}

/**
 * 获取操作日志列表
 * @param {*} req
 * @param {*} res
 */
exports.getOperationLog = (req, res) => {
  // 分页加载
  const page_num = req.query.page_num || 1 //当前的num
  const page_size = req.query.page_size || 10 //当前页的数量
  const username = req.query.username
  const params = [
    (parseInt(page_num) - 1) * parseInt(page_size),
    parseInt(page_size)
  ]
  // 查询
  const selectSql =
    `select a.*, b.username as create_user, c.username as last_update_user from sys_operation_log as a
    left join sys_user as b on a.create_by = b.id
    left join sys_user as c on a.last_update_by = c.id ` +
    (username ? ` where a.username like '%${username}%'` : '') +
    ` limit ?,?`
  // const selectSql = `select * from sys_login_log limit ?,?`
  const pm_list = new Promise((resolve, reject) => {
    db.query(selectSql, params, (err, results) => {
      if (err) return reject(err)
      results.map((item) => {
        item.create_time = formatTime(item.create_time)
        item.last_update_time = formatTime(item.last_update_time)
      })
      resolve(results)
    })
  })

  // 查询数据库总数
  const totalSql =
    `select count(*) as total from sys_operation_log ` +
    (username ? ` where username like '%${username}%'` : '')
  const pm_total = new Promise((resolve, reject) => {
    db.query(totalSql, (err, results) => {
      if (err) return reject(err)
      resolve(results[0].total)
    })
  })

  Promise.all([pm_list, pm_total])
    .then((result) => {
      res.send({
        status: 0,
        message: '获取操作日志列表成功',
        total: result[1],
        data: result[0] || []
      })
    })
    .catch((err) => {
      res.new_send(err)
    })
}
